package cn.edu.cn.tomatoclock;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import cn.edu.cn.tomatoclock.db.RecordManager;
import cn.edu.cn.tomatoclock.domain.Record;
import cn.edu.cn.tomatoclock.util.Util;


public class TomatoClockActivity extends AppCompatActivity {
    private static final long POTATO_TIME = 60*1000*25;
    private static final long PUNISHMENT_TIME = 16*1000;
    private TimeDownCount timeDownCount;
    private TextView myTextview;
    RecordManager recordManager;
    private Handler handler;
    private final Timer timer = new Timer();
    private TimerTask task;
    //=== private parameters and methods for notification =====
    private Button btn_Notify;
    private long[]vibrate = {0,100,200,300};
    private String createNotificationChannel(String channelId, String channlName,int level){
        //針對不同版本的SDK而有的調整 在SDK版本大於26後 需要有channel的設計
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
            //System.out.println("@@@@@@@@@@@@@@@@@@@@@@ THE CURRENT SDK VERSION IS " + Build.VERSION.SDK_INT);
            //初始化NotificationManager來使用Andriod系統的服務
            NotificationManager mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

            String Description = "This is my channel";//對於渠道的描述
            NotificationChannel mChannel = new NotificationChannel(channelId, channlName, level);//level是渠道的重要程度
            mChannel.setDescription(Description);
            mChannel.enableLights(true);
            mChannel.setLightColor(Color.BLUE);
            mChannel.enableVibration(true);
            mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            mChannel.setShowBadge(false);
            mChannel.setLockscreenVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            mNotificationManager.createNotificationChannel(mChannel);
            return channelId;
        }else{
            return null;
        }
    }
    private void activeNotify(String channelId,PendingIntent intent,String title,String context){
        if(channelId!=null){
            NotificationCompat.Builder notification
                    = new NotificationCompat.Builder(TomatoClockActivity.this, channelId)
                    .setContentTitle(title) // 設置下拉清單裡的標題
                    .setContentText(context)  // 設置上下文內容
                    .setContentIntent(intent) //設定Pending intent
                    .setSmallIcon(R.drawable.ic_target) //設定顯示的圖示
                    .setPriority(NotificationCompat.PRIORITY_HIGH)
                    .setAutoCancel(true)
                    .setDefaults(Notification.DEFAULT_ALL) //使用所有預設值，比如聲音，震動，閃屏等等
                    .setVibrate(vibrate)//設定震動的pattern
                    .setTicker("notification on status bar.")// 設置狀態列的顯示的資訊
                    .setWhen(System.currentTimeMillis())// 設置時間發生時間
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(TomatoClockActivity.this);
            //發送通知
            notificationManager.notify(100, notification.build());
        }
    }
    private boolean isTopActivity(Context context, String activityName){
        ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
        String cmpNameTemp = null;
        if(runningTaskInfos != null){
            cmpNameTemp = runningTaskInfos.get(0).topActivity.toString();
            System.out.println("@@@@@@@@@@@@@@cmpNameTemp is "+cmpNameTemp);
            System.out.println("@@@@@@@@@@@@@@activityName is "+activityName);
        }
        if(cmpNameTemp == null){
            System.out.println("@@@@@@@@@@@@@@is null");
            return false;
        }
        return cmpNameTemp.equals(activityName);
    }
    //============================================
    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tomato_clock);
        //===== 設定一個主動提醒的按鈕的功能 ============================================================
        btn_Notify = (Button)findViewById(R.id.btn_Notify);
        btn_Notify.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                //設定按下之後要執行的Activity
                Intent intent = new Intent(TomatoClockActivity.this,MainActivity.class);
                intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
                PendingIntent appIntent = PendingIntent.getActivity(TomatoClockActivity.this, 0, intent, 0);
                //PendingIntent 是一種特殊的Intent,Pending是待定不確定的意思
                String channelId = createNotificationChannel("FirstChannel_ID","FirstChannel_NAME"
                    ,NotificationManager.IMPORTANCE_HIGH);
                activeNotify(channelId,appIntent,"主動觸發的提醒","主動觸發提醒的標題");
            }
        });
       //========================================================================================
        TextView show = (TextView) findViewById(R.id.tomatoView);
        Intent get = getIntent();
        final int minute = get.getIntExtra("minute",1);
        timeDownCount =  new TimeDownCount(minute*1000*60,100){
            @Override
            public void onFinish() {//當計時結束
                final AlertDialog.Builder builder1 = new AlertDialog.Builder(TomatoClockActivity.this);
                builder1.setTitle("提示").setMessage("專注結束!");
                builder1.setPositiveButton("休息五分鐘", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which){
                        Intent intent = new Intent();
                        intent.setClass(TomatoClockActivity.this, TomatoClockFiveMinutesActivity.class);
                        startActivity(intent);
                        TomatoClockActivity.this.finish();
                    }
                });
                builder1.setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(TomatoClockActivity.this,MainActivity.class);
                        startActivity(intent);
                        timeDownCount.cancel();
                    }
                });
                builder1.create();
                builder1.show();//顯示提醒訊息

//               if(!isTopActivity(getApplication(),"TomatoClockActivity")){//如果當前的頁面不在最前面的話才去跳提醒。
                Intent intent = new Intent(TomatoClockActivity.this,TomatoClockActivity.class);//選擇不切換頁面
                intent.setFlags( Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_CLEAR_TASK);
                PendingIntent appIntent = PendingIntent.getActivity(TomatoClockActivity.this, 0, intent, 0);
                String channelId = createNotificationChannel("SecondChannel_ID","SecondChannel_NAME"
                        ,NotificationManager.IMPORTANCE_HIGH);

                activeNotify(channelId,appIntent,"時間到了的提醒","休息時間到囉");

                //============ 紀錄專注的次數與時間 ========================================
                recordManager = new RecordManager(TomatoClockActivity.this);
                if(recordManager.findByName("專注次數") == null){
                    Record record = new Record("專注次數","0次");
                    recordManager.add(record);
                }
                Record temp1 = recordManager.findByName("專注次數");
                String result1 = Integer.parseInt(temp1.getRecordContent().split("次")[0])+1+"次";
                recordManager.updateByName(temp1.getRecordName(),result1);

                if(recordManager.findByName("專注時間") == null){
                    Record record = new Record("專注時間","0分鐘");
                    recordManager.add(record);
                }
                Record temp2 = recordManager.findByName("專注時間");
                String result2 = (Integer.parseInt(temp2.getRecordContent().split("分")[0])+minute)+"分鐘";
                recordManager.updateByName(temp2.getRecordName(),result2);
                //==========================================================================
            }
        };
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                if(msg.what == 1 && Util.isApplicationBroughtToBackground(TomatoClockActivity.this)){
                    myTextview = new TextView(TomatoClockActivity.this);
                    final AlertDialog.Builder builder = new AlertDialog.Builder(TomatoClockActivity.this);
                    builder.setTitle("警告").setView(myTextview);
                    final CountDownTimer countDownTimer = new CountDownTimer(PUNISHMENT_TIME,1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            myTextview.setText(millisUntilFinished/1000+"s後專注將結束!");
                            myTextview.setPadding(75,0,0,0);
                        }
                        @Override
                        public void onFinish() {
                            Intent intent = new Intent(TomatoClockActivity.this,MainActivity.class);
                            startActivity(intent);
                        }
                    };
                    builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            countDownTimer.cancel();
                        }
                    });
                    countDownTimer.start();
                    builder.create();
                    builder.show();
                }
                super.handleMessage(msg);
            }
        };
        task = new TimerTask() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        timeDownCount.setClockShow(show);
        timeDownCount.start();
        timer.schedule(task, 2000, 1000);
    }

    public void back(View btn){
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示").setPositiveButton("確認返回", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //open activity
                Intent back = new Intent(TomatoClockActivity.this,MainActivity.class);
                startActivity(back);
            }
        }).setNegativeButton("繼續計時", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create();
        builder.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timeDownCount != null){
            timeDownCount.cancel();
        }
    }
}